package com.heima.behavior.service.Impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.beans.Beans;
import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        //1.校验参数
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数异常!");
        }
        //1.1点赞需要登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"点赞需要登录!");
        }
        Integer userId = user.getId();
        //2.根据当前登录用户id查询行为实体对象
        ApBehaviorEntry apBehaviorEntry= apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        //3.如果是点赞操作  判断是否已经点过赞
        ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()).and("type").is(dto.getType())), ApLikesBehavior.class);
        if(dto.getOperation()==0) {
            if (apLikesBehavior != null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "你已经点过赞了!");
            }
            //4.如果没有点过赞,则添加点赞数据
            ApLikesBehavior likesBehavior = new ApLikesBehavior();
            BeanUtils.copyProperties(dto, likesBehavior);
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(likesBehavior);
            return ResponseResult.okResult();
        }
        //5.如果是取消点赞,则删除点赞数据
            mongoTemplate.remove(apLikesBehavior);
        return ResponseResult.okResult();
    }
}
